package com.sifang.POI.dianping;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;



public class PreJobCommand extends MultiThreadsCommand {
	
	private int processedCount;

	public int getTotalPage(String url) throws IOException, XPatherException {
		TagNode node = WebUtil.cleanUrl(url);
		Object[] results = node.evaluateXPath("//div[@class='Pages']");
		if (results.length == 0) {
			results = node.evaluateXPath("//div[@class='noResult']");
			return 1 - results.length;
		} else {
			TagNode pagesNode = (TagNode) results[0];
			results = pagesNode.evaluateXPath("//a[@class='PageLink']");
			TagNode lastPageNode = (TagNode) results[results.length - 1];
			String title = lastPageNode.getAttributeByName("title");
			return Integer.parseInt(title);
		}
	}

	public PreJobCommand() {
		this(DEFAULT_MAX_THREADS);
	}

	public PreJobCommand(int maxThreads) {
		super(maxThreads);
	}
	
	private synchronized int increaseProcessedCount() {
		return ++this.processedCount;
	}

	@Override
	protected List<? extends Runnable> getNextBatchWorks() {
		Session s = DpDb.getInstance().openSession();
		String query = String.format("from PreJob preJob where preJob.status != %d", JobStatus.STATUS_PROCESSED);
		@SuppressWarnings("unchecked")
		List<PreJob> preJobs = s.createQuery(query).setMaxResults(DpCmd.getInstance().getDbReadBatchSize()).list();
		s.close();
		List<Workitem> works = new ArrayList<Workitem>();
		for (PreJob preJob : preJobs) {
			works.add(new Workitem(preJob));
		}
		return works;
	}
	
	class Workitem implements Runnable {
		private PreJob preJob;

		public Workitem(PreJob preJob) {
			this.preJob = preJob;
		}

		@Override
		public void run() {
			String url = preJob.getUrl();
			int totalPage = 0;
			
			try {
				totalPage = getTotalPage(url);
			} catch (Exception e) {
				e.printStackTrace();
				return;
			}
			
			Session s = DpDb.getInstance().openSession();
			s.beginTransaction();
			
			preJob.setStatus(JobStatus.STATUS_PROCESSED);
			preJob.setTotalPage(totalPage);
			s.update(preJob);
			
			for (int i = 1; i <= totalPage; i++) {
				String pageUrl = String.format("%sp%d", url, i);
				String query = String.format("from Job job where job.url = '%s'", pageUrl);
				Job job = (Job) s.createQuery(query).setMaxResults(1).uniqueResult();

				if (job == null) {
					job = new Job(pageUrl, JobStatus.STATUS_NONE, 0);
					s.save(job);
				}
			}
			
			s.getTransaction().commit();
			s.close();
			
			String status = String.format("%d | %s", increaseProcessedCount(), getElapseTimeString());
			String shortUrl = url.substring(url.lastIndexOf('/') + 1);
			status = String.format("\r%-20s%30s", shortUrl, status);
			System.out.print(status);
		}
	}
	
	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		new PreJobCommand().execute();
	}

}
